package org.jash.shop2202.shop

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Route
import org.jash.shop2202.BR
import org.jash.shop2202.R
import org.jash.shop2202.databinding.FragmentCategoryBinding
import org.jash.shop2202.entity.Category
import org.jash.shop2202.entity.Goods
import org.jash.shop2202.mvvm.BaseFragment
import org.jash.shop2202.utils.CommonAdapter
import org.jash.shop2202.utils.Event

@Route(path = "/shop/category")
class CategoryFragment : BaseFragment<FragmentCategoryBinding, CategoryViewModel>() {

    private val categoryAdapter by lazy { CommonAdapter<Category>({R.layout.item_category to BR.category}) }
    private val subcategoryAdapter by lazy { CommonAdapter<Category>({R.layout.item_subcategory to BR.category}) }
    private val productAdapter by lazy { CommonAdapter<Goods>({R.layout.item_goods to BR.goods}) }
    override fun initData() {
        viewModel.goodsLiveData.observe(viewLifecycleOwner) {
            productAdapter.clear()
            productAdapter += it
        }
        viewModel.categoryLiveData.observe(viewLifecycleOwner) {
            categoryAdapter += it
            it[0].showSubcategory()
        }
        viewModel.loadCategory()
    }

    override fun initView() {
        binding.category.adapter = categoryAdapter
        binding.subcategory.adapter = subcategoryAdapter
        binding.product.adapter = productAdapter
    }

    @Event("展示子分类")
    fun showSubcategory(list: List<Category>) {
        categoryAdapter.data.forEach { it.notifyPropertyChanged(BR.selected) }
        subcategoryAdapter.clear()
        subcategoryAdapter += list
        productAdapter.clear()
        if (list.isNotEmpty()) {
            list[0].showProduct()
        }

    }
    @Event("展示商品")
    fun showProduct(cid:Int) {
        viewModel.loadGoods(cid, 1, 20)
    }
}